package com.hhe.datax_transfer.exception;

import com.hhe.datax_transfer.common.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * 全局异常控制
 *
 * @author HHe
 * @version V1.0
 * @date 2021/1/8 16:31
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Object ExceptionHandler(Exception e) {
        log.error("错误异常类：" + e.getClass().getTypeName() + "异常信息：" + e.getMessage());
        return new JsonResult("201", "系统错误", "");
    }

    /**
     * 服务层异常
     *
     * @version V1.0
     * @author HHe
     * @date 2021/1/8 16:33
     */
    @ExceptionHandler(ServiceException.class)
    public Object serviceExceptionHandler(ServiceException e) {
        log.error(e.getMessage());
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(e.getCode());
        jsonResult.setMessage(e.getMessage());
        return jsonResult;
    }

    /**
     * 验证框架异常
     *
     * @version V1.0
     * @author HHe
     * @date 2021/1/13 9:19
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Object ConstraintViolationExceptionHandler(ConstraintViolationException e) {
        log.error(e.getMessage());
        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining("|"));
        return new JsonResult("201", message, "");
    }
}
